from PyQt5.QtWidgets import QDialog, QLineEdit, QComboBox, QFormLayout, QPushButton, QHBoxLayout, QLabel, QMessageBox
from core.connectors.db_connector import DatabaseConnector


class ConnectionDialog(QDialog):
    def __init__(self, parent=None, is_edit=False, connection_name="", connection_info=None):
        super().__init__(parent)
        self.is_edit = is_edit
        self.connection_name = connection_name
        self.connection_info = connection_info or {}
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("编辑连接" if self.is_edit else "新增连接")
        self.resize(400, 350)

        layout = QFormLayout()

        # 连接名称
        if self.is_edit:
            self.name_input = QLineEdit(self.connection_name)
            self.name_input.setReadOnly(True)  # 编辑模式下连接名称不可修改
        else:
            self.name_input = QLineEdit()
        layout.addRow("连接名称：", self.name_input)

        # 数据库类型
        self.type_input = QComboBox()
        self.type_input.addItems(["MySQL", "PostgreSQL"])
        self.type_input.setCurrentText(self.connection_info.get("type", "MySQL"))
        layout.addRow("数据库类型：", self.type_input)

        # 主机地址
        self.host_input = QLineEdit(self.connection_info.get("host", "localhost"))
        layout.addRow("主机地址：", self.host_input)

        # 端口
        self.port_input = QLineEdit(str(self.connection_info.get("port", 3306)))
        layout.addRow("端口：", self.port_input)

        # 用户名
        self.user_input = QLineEdit(self.connection_info.get("user", ""))
        layout.addRow("用户名：", self.user_input)

        # 密码
        self.password_input = QLineEdit(self.connection_info.get("password", ""))
        self.password_input.setEchoMode(QLineEdit.Password)
        layout.addRow("密码：", self.password_input)

        # 数据库名称
        self.database_input = QLineEdit(self.connection_info.get("database", ""))
        layout.addRow("数据库名称：", self.database_input)

        # 测试结果标签
        self.test_result_label = QLabel("")
        layout.addRow("测试结果：", self.test_result_label)

        # 保存、测试和取消按钮
        button_layout = QHBoxLayout()
        self.save_button = QPushButton("保存")
        self.save_button.clicked.connect(self.accept)
        self.test_button = QPushButton("测试连接")
        self.test_button.clicked.connect(self.test_connection)
        self.cancel_button = QPushButton("取消")
        self.cancel_button.clicked.connect(self.reject)

        button_layout.addWidget(self.save_button)
        button_layout.addWidget(self.test_button)
        button_layout.addWidget(self.cancel_button)
        layout.addRow(button_layout)

        self.setLayout(layout)

    def test_connection(self):
        """测试数据库连接"""
        connection_info = {
            "type": self.type_input.currentText(),
            "host": self.host_input.text(),
            "port": int(self.port_input.text()),
            "user": self.user_input.text(),
            "password": self.password_input.text(),
            "database": self.database_input.text(),
        }
        try:
            # 使用 DBConnector 测试连接
            connector = DatabaseConnector.create_connector(connection_info)
            r,d = connector.test_connection()
            if r:
                self.test_result_label.setText("测试成功！")
                QMessageBox.information(self, "成功", "数据库连接测试成功！")
                connector.close()
            else:
                self.test_result_label.setText("测试失败")
                QMessageBox.critical(self, "错误", f"数据库连接测试失败：{d}")
        except Exception as e:
            self.test_result_label.setText("测试失败")
            QMessageBox.critical(self, "错误", f"数据库连接测试失败：{e}")

    def get_connection_data(self):
        """获取连接名称和详细信息"""
        connection_name = self.name_input.text()
        connection_info = {
            "type": self.type_input.currentText(),
            "host": self.host_input.text(),
            "port": int(self.port_input.text()),
            "user": self.user_input.text(),
            "password": self.password_input.text(),
            "database": self.database_input.text(),
        }
        return connection_name, connection_info